from flask import Blueprint, jsonify, request
from models.auth import UserModel
from exts import db


bp = Blueprint('user', __name__, url_prefix='/api')

@bp.route('/index')
def getUser():
    return "user"

@bp.route('/users', methods=['GET'])
def get_users():
    users = UserModel.query.all()
    return jsonify([user.to_dict() for user in users])

@bp.route('/create', methods=['POST'])
def create_user():
    username = request.json.get('username')
    email = request.json.get('email')

    user = UserModel(username=username, email=email)
    db.session.add(user)
    db.session.commit()

    return jsonify({"msg": "User created!", "user": user.to_dict()})

@bp.route('/query/<username>', methods=['GET'])
def get_user(username):
    user = UserModel.query.filter_by(username=username).first()
    if user:
        return jsonify(user.to_dict())
    else:
        return jsonify({"msg": "User not found"})

@bp.route('/update/<username>', methods=['PUT'])
def update_email(username):
    user = UserModel.query.filter_by(username=username).first()
    if not user:
        return jsonify({"msg": "User not found"})

    new_email = request.json.get('email')
    user.email = new_email
    db.session.commit()

    return jsonify({"msg": "Email updated", "user": user.to_dict()})

@bp.route('/delete/<username>', methods=['DELETE'])
def delete_user(username):
    user = UserModel.query.filter_by(username=username).first()
    if not user:
        return jsonify({"msg": "User not found"})

    db.session.delete(user)
    db.session.commit()

    return jsonify({"msg": "User deleted"})
